package com.kfm.hotel.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kfm.hotel.mapper.SysUserMapper;
import com.kfm.hotel.pojo.SysUser;
import com.kfm.hotel.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper mapper;

    @Override
    public SysUser login(SysUser sysUser) {
        // 密码加密
        sysUser.setPassword(new MD5(sysUser.getUsername().getBytes(StandardCharsets.UTF_8)).digestHex(sysUser.getPassword()));
        List<SysUser> sysUsers = mapper.selectWithSysUser(sysUser);
        return sysUsers.size() == 1? sysUsers.get(0) : null;
    }

    @Override
    public PageInfo<SysUser> list(Integer pageNumber, Integer pageSize, SysUser sysUser) {
        PageHelper.startPage(pageNumber, pageSize);
        List<SysUser> page = mapper.selectWithSysUser(sysUser);
        return new PageInfo<SysUser>(page);
    }

    @Override
    public int addUser(SysUser sysUser) {
        if (ObjectUtils.isEmpty(sysUser.getId())){
            // 新增
            sysUser.setId(String.valueOf(IdUtil.getSnowflakeNextId()));
            // TODO(密码加密)
            sysUser.setPassword(new MD5(sysUser.getUsername().getBytes(StandardCharsets.UTF_8)).digestHex(sysUser.getPassword()));
            return mapper.insertSelective(sysUser);
        } else{
            // 修改
            return mapper.updateSelectiveById(sysUser);
        }
    }

    @Override
    public int updateUser(SysUser sysUser) {
        return mapper.updateSelectiveById(sysUser);
    }
}
